<?php

namespace Home\Controller;

class OrderController extends BaseMemberController
{

    function _initialize()
    {
        parent::_initialize();
        $this->_user_id = session('visitor.user_id');
        $this->_user_name = session('visitor.user_name');
        $this->_user_no = session('visitor.user_no');
        $this->_real_name = session('visitor.real_name');

        $this->_Cart_mod = M('cart');
        $this->_Order_mod = M('order');
        $this->_Shipping_mod = M('shipping');
    }

    /**
     * @api {get} /index.php?m=Home&c=Order&a=index 返回下单内容
     */
    function index()
    {
        //ECMALL的全局变量
        $goods_list = D('cart')->get_goods(0, $this->_user_id, I('request.rec_ids'));
        if (empty($goods_list)) {
            render('10400', '没有商品加入购物车');
        }

        $goods_beyond = '';
        $no_shipping = '';
        foreach ($goods_list as $store_id => $item) {
            $goods_list[$store_id]['type'] = 'material';
            $goods_list[$store_id]['otype'] = 'normal';
            $goods_list[$store_id]['allow_coupon'] = true;
            //每个店铺的发货方式
            $goods_list[$store_id]['shipping'] = D('shipping')->get_list($store_id);
            if (!$goods_list[$store_id]['shipping']) {
                if (!$no_shipping) {
                    $no_shipping = $item['store_name'];
                } else {
                    $no_shipping .= '，' . $item['store_name'];
                }
            }
            //检查库存
            foreach ($item['goods'] as $goods) {
                if ($goods['quantity'] > intval($goods['stock'])) {
                    if (!$goods_beyond) {
                        $goods_beyond = $goods['goods_name'];
                    } else {
                        $goods_beyond .= '，' . $goods['goods_name'];
                    }
                }
            }
            //检查满包邮
            $goods_list[$store_id]['is_free_fee'] = 0;
            $goods_list[$store_id]['free_fee_name'] = '';
            $logic1 = FALSE;
            if ($item['enable_free_fee']) {
                (($item['amount'] > $item['amount_for_free_fee']) && ($item['amount_for_free_fee'] > 0)) && $logic1 = true;
                $logic2 = ($item['quantity'] >= $item['acount_for_free_fee']) && ($item['acount_for_free_fee'] > 0);
                if ($logic1 || $logic2) {
                    $logic2 && $title = sprintf('满%d件包邮', $item['acount_for_free_fee']);
                    $logic1 && $title = sprintf('满%s元包邮', $item['amount_for_free_fee']);
                    $goods_list[$store_id]['is_free_fee'] = 1;
                    $goods_list[$store_id]['free_fee_name'] = $title;
                }
            }
            //获取优惠券
            $time = time();
            $goods_list[$store_id]['coupon_list'] = M('CouponSn')->alias('couponsn')->join('LEFT JOIN ' . C('DB_PREFIX') . 'coupon coupon  ON couponsn.coupon_id=coupon.coupon_id')->where("coupon.store_id = " . $store_id . " AND couponsn.remain_times >=1 " . "AND couponsn.user_id=" . $this->_user_id . " " . "AND coupon.start_time <= " . $time . " AND coupon.end_time >= " . $time . " AND coupon.min_amount <= " . $item['amount'])->select();

            //计算商品的总抵扣积分
            $total_integral_max_exchange = 0; #共可使用多少积分进行抵扣

            foreach ($item['items'] as $goods) {

                // 因为一个订单可能包含多个商品,一个商品可能购买了M件，那么可使用的积分便是 N*M 之和
                $goods_integral = M('goods')->where('goods_id=' . $goods['goods_id'])->find(); #当前产品设置的积分抵扣额
                $total_integral_max_exchange += $goods_integral['integral_max_exchange'] * $goods['quantity'];
            }
            $goods_list[$store_id]['total_integral_max_exchange'] = $total_integral_max_exchange;
            $total_amount += $goods_list[$store_id]['amount'];
        }
        //定义用户可用积分与余额
        $member = M('member')->field('money,integral')->where('user_id=' . $this->_user_id)->find();
        //获取收货地址
        $address = M('address')->where('is_default = 1 AND user_id=' . $this->_user_id)->find();


        if ($goods_beyond) {
            render('10405', '购物车中商品库存不足：' . $goods_beyond);
        }
        if ($no_shipping) {
            render('10406', '店铺没有启用配送方式：' . $no_shipping);
        }
        if (!IS_POST) {
            $goods_list = array_values($goods_list);
            foreach ($goods_list as $key => $val) {
                $goods_list[$key]['shipping'] = array_values($goods_list[$key]['shipping']);
            }
            render('10000', '', array('total_amount' => $total_amount, 'goods_list' => $goods_list, 'member' => $member, 'address' => $address, 'integral_enabled' => intval(C('integral_enabled')), 'integral_seller' => floatval(C('integral_seller'))));
        } else {
            //获得支付的订单ids
            $order_ids = '';

            $coupon_sn_array = I('post.coupon_sn');
            $use_integral_array = I('post.use_integral');
            $rec_ids = I('request.rec_ids');
            if (!$rec_ids) {
                render('10515', '购物车记录ID为空');
            }
            foreach ($goods_list as $key => $goods_info) {
                //优惠券的处理
                if ($goods_info['allow_coupon'] && !empty($coupon_sn_array)) {

                    if (!empty($coupon_sn_array[$key])) {
                        $coupon = M('Coupon')->alias('coupon')->join('LEFT JOIN ' . C('DB_PREFIX') . 'coupon_sn couponsn  ON couponsn.coupon_id=coupon.coupon_id')->where("coupon_sn='" . $coupon_sn_array[$key] . "' AND store_id = " . $goods_info['store_id'])->find();
                        if (empty($coupon)) {
                            render('10501', '优惠券不存在');
                        }
                        if ($coupon['remain_times'] < 1) {
                            render('10502', '优惠券已用完');
                        }
                        $time = time();
                        if ($coupon['start_time'] > $time) {
                            render('10503', '优惠券无效');
                        }

                        if ($coupon['end_time'] < $time) {
                            render('10504', '优惠券过期');
                        }
                        if ($coupon['min_amount'] > $goods_info['amount']) {
                            render('10505', '未达到优惠券使用条件');
                        }
                        unset($time);
                        $goods_list[$key]['discount'] = $coupon['coupon_value'];
                    }
                }
                if (!empty($use_integral_array[$key]) && intval(C('integral_enabled')) && intval($use_integral_array[$key])) {
                    //用户提交使用的积分额度
                    $use_integral = intval($use_integral_array[$key]);

                    $total_integral_max_exchange = $goods_info['total_integral_max_exchange'];
                    if ($use_integral > $total_integral_max_exchange) {
                        render('10506', '此订单最多可以使用 ' . $total_integral_max_exchange . '积分');
                    }
                    //获取当前用户可用积分
                    if ($use_integral > $member['integral']) {
                        render('10507', '对不起，你没有足够的积分！你目前的积分值为：' . $member['integral']);
                    }
                    //获取抵扣金额
                    $goods_list[$key]['discount'] += $use_integral * floatval(C('integral_seller'));
                    //扣除积分记录,更新信息
                    D('Integrallog')->change_integral_seller($this->_user_id, $use_integral);
                }

                $_post_data = array();
                $_post_data['addr_id'] = I('request.addr_id');
//                $_post_data['shipping_id'] = I('post.shipping_id_' . $key);
                $_post_data['shipping_id'] = $_POST['shipping_id'][$key];
                $_post_data['postscript'] = $_POST['postscript'][$key];
                $_post_data['use_integral'] = $_POST['use_integral'][$key];
                $_post_data['coupon_sn'] = $_POST['coupon_sn'][$key];
                $_post_data['pd_amount'] = I('request.pd_amount');
                /* 将这些信息传递给订单类型处理类生成订单(你根据我提供的信息生成一张订单) */
                $order_id = D('Order')->submit_order(array(
                    'goods_info' => $goods_list[$key], //商品信息（包括列表，总价，总量，所属店铺，类型）,可靠的!
                    'post' => $_post_data, //用户填写的订单信息
                ));

                /* 下单完成后清理商品，如清空购物车，或将团购拍卖的状态转为已下单之类的 */
                $this->_clear_goods($order_id, $_POST['coupon_sn'][$key]);

                /* 减去商品库存 */
                D('Order')->change_stock('-', $order_id);

                /* 获取订单信息 */
                $order_info = M('Order')->where('order_id=' . $order_id)->find();

                /* 记录订单操作日志 */
                M('OrderLog')->add(array(
                    'order_id' => $order_id,
                    'operator' => addslashes($this->_user_name),
                    'order_status' => '',
                    'changed_status' => '下订单',
                    'remark' => '买家下单',
                    'log_time' => time(),
                    'operator_type' => 'buyer'
                ));


                /* 更新下单次数 */
                $goods_ids = array();
                foreach ($goods_info['items'] as $goods) {
                    $goods_ids[] = $goods['goods_id'];
                }
                M('GoodsStatistics')->where('goods_id IN(' . implode(',', $goods_ids) . ')')->setInc('orders');


                if ($order_ids == '') {
                    $order_ids .= $order_id;
                } else {
                    $order_ids .= ',' . $order_id;
                }
            }
            render('10000', '', array('order_ids' => $order_ids));
        }
    }

    function get_list()
    {
        if (!I('request.spec_id')) {
            render('10400', '请选择商品');
        }
        if (!I('request.number')) {
            render('10400', '请选择数量');
        }
        //ECMALL的全局变量
        $goods_lists = M('goods')->field(C('DB_PREFIX') . 'store.state,' . C('DB_PREFIX') . 'store.store_name,' . C('DB_PREFIX') . 'goods.*,' . C('DB_PREFIX') . 'goods_spec.*')
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'store  ON ' . C('DB_PREFIX') . 'goods.store_id = ' . C('DB_PREFIX') . 'store.store_id')
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'goods_spec  ON ' . C('DB_PREFIX') . 'goods.goods_id = ' . C('DB_PREFIX') . 'goods_spec.goods_id')
            ->where('spec_id=' . I('request.spec_id'))
            ->find();
        $goods_lists['spec_name_1'] && $goods_lists['spec_1value'] ? $goods_lists['specification'] .= $goods_lists['spec_name_1'] . ':' . $goods_lists['spec_1value'] . ' ' : '';
        $goods_lists['spec_name_2'] && $goods_lists['spec_2'] ? $goods_lists['specification'] .= $goods_lists['spec_name_2'] . ':' . $goods_lists['spec_2'] . ' ' : '';
        $goods_lists['spec_name_3'] && $goods_lists['spec_3'] ? $goods_lists['specification'] .= $goods_lists['spec_name_3'] . ':' . $goods_lists['spec_3'] . ' ' : '';
        $goods_lists['spec_name_4'] && $goods_lists['spec_4'] ? $goods_lists['specification'] .= $goods_lists['spec_name_4'] . ':' . $goods_lists['spec_4'] . ' ' : '';
        $goods_lists['quantity'] = I('request.number');
        $goods_lists['spec_1'] ? $goods_image = $goods_lists['spec_1'] : $goods_image = $goods_lists['default_image'];
        $goods_lists['goods_image'] = $goods_image;
        $temp_array = array();
        array_push($temp_array, $goods_lists);
        $goods_list = array();
        $goods_list[$goods_lists['store_id']] = array(
            'goods_amount' => round($goods_lists['price'] * I('request.number') + $goods_lists['tax_price'] * I('request.number'), 2),
            'price_amount' => round($goods_lists['price'] * I('request.number'), 2),
            'amount' => round($goods_lists['price'] * I('request.number'), 2),
            'tax_price_amount' => round($goods_lists['tax_price'] * I('request.number'), 2),
            'total_price' => round($goods_lists['price'] * I('request.number') + $goods_lists['tax_price'] * I('request.number'), 2),
            'store_id' => $goods_lists['store_id'],
            'store_name' => $goods_lists['store_name'],
            'kinds' => 1,
            'goods_image' => $goods_image,
            'quantity' => I('request.number'),
            'items' => $temp_array,
        );
        if (empty($goods_list)) {
            render('10400', '查询商品失败');
        }

        $goods_beyond = '';
        $no_shipping = '';
        foreach ($goods_list as $store_id => $item) {
            $goods_list[$store_id]['type'] = 'material';
            $goods_list[$store_id]['otype'] = 'normal';
            $goods_list[$store_id]['allow_coupon'] = true;
            //每个店铺的发货方式
            $goods_list[$store_id]['shipping'] = D('shipping')->get_list($store_id);
            if (!$goods_list[$store_id]['shipping']) {
                if (!$no_shipping) {
                    $no_shipping = $item['store_name'];
                } else {
                    $no_shipping .= '，' . $item['store_name'];
                }
            }
            //检查库存
            foreach ($item['goods'] as $goods) {
                if ($goods['quantity'] > intval($goods['stock'])) {
                    if (!$goods_beyond) {
                        $goods_beyond = $goods['goods_name'];
                    } else {
                        $goods_beyond .= '，' . $goods['goods_name'];
                    }
                }
            }
            //检查满包邮
            $goods_list[$store_id]['is_free_fee'] = 0;
            $goods_list[$store_id]['free_fee_name'] = '';
            $logic1 = FALSE;
            if ($item['enable_free_fee']) {
                (($item['price_amount'] > $item['amount_for_free_fee']) && ($item['amount_for_free_fee'] > 0)) && $logic1 = true;
                $logic2 = ($item['quantity'] >= $item['acount_for_free_fee']) && ($item['acount_for_free_fee'] > 0);
                if ($logic1 || $logic2) {
                    $logic2 && $title = sprintf('满%d件包邮', $item['acount_for_free_fee']);
                    $logic1 && $title = sprintf('满%s元包邮', $item['amount_for_free_fee']);
                    $goods_list[$store_id]['is_free_fee'] = 1;
                    $goods_list[$store_id]['free_fee_name'] = $title;
                }
            }
            //获取优惠券
            $time = time();
            $goods_list[$store_id]['coupon_list'] = M('CouponSn')->alias('couponsn')->join('LEFT JOIN ' . C('DB_PREFIX') . 'coupon coupon  ON couponsn.coupon_id=coupon.coupon_id')->where("coupon.store_id = " . $store_id . " AND couponsn.remain_times >=1 " . "AND couponsn.user_id=" . $this->_user_id . " " . "AND coupon.start_time <= " . $time . " AND coupon.end_time >= " . $time . " AND coupon.min_amount <= " . $item['amount'])->select();
            //计算商品的总抵扣积分
            $total_integral_max_exchange = 0; #共可使用多少积分进行抵扣

            foreach ($item['items'] as $goods) {
                // 因为一个订单可能包含多个商品,一个商品可能购买了M件，那么可使用的积分便是 N*M 之和
                $goods_integral = M('goods')->where('goods_id=' . $goods['goods_id'])->find(); #当前产品设置的积分抵扣额
                $total_integral_max_exchange += $goods_integral['integral_max_exchange'] * $goods['quantity'];
            }
            $goods_list[$store_id]['total_integral_max_exchange'] = $total_integral_max_exchange;
            $total_amount += $goods_list[$store_id]['amount'];
        }
        //定义用户可用积分与余额
        $member = M('member')->field('money,integral,user_no,real_name')->where('user_id=' . $this->_user_id)->find();
        //获取收货地址
        $address = M('address')->where('is_default = 1 AND user_id=' . $this->_user_id)->find();

        if ($goods_beyond) {
            render('10405', '购物车中商品库存不足：' . $goods_beyond);
        }
        if ($no_shipping) {
            render('10406', '店铺没有启用配送方式：' . $no_shipping);
        }
        if (!IS_POST) {
            $goods_list = array_values($goods_list);
            foreach ($goods_list as $key => $val) {
                $goods_list[$key]['shipping'] = array_values($goods_list[$key]['shipping']);
            }
            render('10000', '', array('total_amount' => $total_amount, 'goods_list' => $goods_list, 'member' => $member, 'address' => $address, 'integral_enabled' => intval(C('integral_enabled')), 'integral_seller' => floatval(C('integral_seller'))));
        } else {
            //获得支付的订单ids
            $order_ids = '';

            $coupon_sn_array = I('post.coupon_sn');
            $use_integral_array = I('post.use_integral');
            if (!$member['real_name'] || !$member['user_no']) {
                render('10400', '请补全身份证号和姓名');
            }
//            $rec_ids = I('request.rec_ids');
//            if (!$rec_ids) {
//                render('10515', '购物车记录ID为空');
//            }
            foreach ($goods_list as $key => $goods_info) {
                //优惠券的处理
                if ($goods_info['allow_coupon'] && !empty($coupon_sn_array)) {

                    if (!empty($coupon_sn_array[$key])) {
                        $coupon = M('Coupon')->alias('coupon')->join('LEFT JOIN ' . C('DB_PREFIX') . 'coupon_sn couponsn  ON couponsn.coupon_id=coupon.coupon_id')->where("coupon_sn='" . $coupon_sn_array[$key] . "' AND store_id = " . $goods_info['store_id'])->find();
                        if (empty($coupon)) {
                            render('10501', '优惠券不存在');
                        }
                        if ($coupon['remain_times'] < 1) {
                            render('10502', '优惠券已用完');
                        }
                        $time = time();
                        if ($coupon['start_time'] > $time) {
                            render('10503', '优惠券无效');
                        }

                        if ($coupon['end_time'] < $time) {
                            render('10504', '优惠券过期');
                        }
                        if ($coupon['min_amount'] > $goods_info['amount']) {
                            render('10505', '未达到优惠券使用条件');
                        }
                        unset($time);
                        $goods_list[$key]['discount'] = $coupon['coupon_value'];
                    }
                }
                if (!empty($use_integral_array[$key]) && intval(C('integral_enabled')) && intval($use_integral_array[$key])) {
                    //用户提交使用的积分额度
                    $use_integral = intval($use_integral_array[$key]);

                    $total_integral_max_exchange = $goods_info['total_integral_max_exchange'];
                    if ($use_integral > $total_integral_max_exchange) {
                        render('10506', '此订单最多可以使用 ' . $total_integral_max_exchange . '积分');
                    }
                    //获取当前用户可用积分
                    if ($use_integral > $member['integral']) {
                        render('10507', '对不起，你没有足够的积分！你目前的积分值为：' . $member['integral']);
                    }
                    //获取抵扣金额
                    $goods_list[$key]['discount'] += $use_integral * floatval(C('integral_seller'));
                    //扣除积分记录,更新信息
                    D('Integrallog')->change_integral_seller($this->_user_id, $use_integral);
                }
                $_post_data = array();
                $_post_data['addr_id'] = I('request.addr_id');
//                $_post_data['shipping_id'] = I('post.shipping_id_' . $key);
                $_post_data['shipping_id'] = $_POST['shipping_id'][$key];
                $_post_data['postscript'] = $_POST['postscript'][$key];
                $_post_data['use_integral'] = $_POST['use_integral'][$key];
                $_post_data['coupon_sn'] = $_POST['coupon_sn'][$key];
//                lichen 2019/5/25 start
//                lichen 2019/5/25 end
                $_post_data['pd_amount'] = I('request.pd_amount');
                /* 将这些信息传递给订单类型处理类生成订单(你根据我提供的信息生成一张订单) */
                $order_id = D('Order')->submit_order(array(
                    'goods_info' => $goods_list[$key], //商品信息（包括列表，总价，总量，所属店铺，类型）,可靠的!
                    'post' => $_post_data, //用户填写的订单信息
                ));

                /* 下单完成后清理商品，如清空购物车，或将团购拍卖的状态转为已下单之类的 */
                I('post.rec_ids') ? $this->_clear_goods($order_id, $_POST['coupon_sn'][$key]) : null;

                /* 减去商品库存 */
                D('Order')->change_stock('-', $order_id);

                /* 获取订单信息 */
                $order_info = M('Order')->where('order_id=' . $order_id)->find();

                /* 记录订单操作日志 */
                M('OrderLog')->add(array(
                    'order_id' => $order_id,
                    'operator' => addslashes($this->_user_name),
                    'order_status' => '',
                    'changed_status' => '下订单',
                    'remark' => '买家下单',
                    'log_time' => time(),
                    'operator_type' => 'buyer'
                ));


                /* 更新下单次数 */
                $goods_ids = array();
                foreach ($goods_info['items'] as $goods) {
                    $goods_ids[] = $goods['goods_id'];
                }
                M('GoodsStatistics')->where('goods_id IN(' . implode(',', $goods_ids) . ')')->setInc('orders');


                if ($order_ids == '') {
                    $order_ids .= $order_id;
                } else {
                    $order_ids .= ',' . $order_id;
                }
            }

            /* 获取订单明细信息 */
            $order_goods = M('order_goods')->where(array('order_id' => $order_id))->select();
            $order_extm = M('order_extm')->where(array('order_id' => $order_id))->find();
            $send_data = $order_info;
            $send_data['order_goods'] = $order_goods;
            $send_data['order_extm'] = $order_extm;
            /* 获取商品明细信息 */
//            $send_data['goods_spec'] = array();
//            $send_data['goods'] = array();
//
//
//            $send_data['goods'] = array();
//            $send_data['storestock'] = array();
//            $send_data['tax'] = array();
//            $send_data['unit'] = array();
            foreach ($send_data['order_goods'] as $k => $v) {
                $temp_goods_spec = M('goods_spec')->where(array('spec_id' => $send_data['order_goods'][$k]['spec_id']))->find();
                $temp_goods = M('goods')->where(array('goods_id' => $send_data['order_goods'][$k]['goods_id']))->find();
                $temp_storestock = M('storestock')->where(array('storestock_id' => $temp_goods_spec['spec_3value']))->find();
                $temp_tax = M('my_tax')->where(array('tax_id' => $temp_goods['tax_id']))->find();
                $temp_unit = M('unit')->where(array('id' => $temp_goods['unit_id']))->find();
                $temp_country = M('country_info')->where(array('id' => $temp_goods['country_id']))->find();
                $temp_wrap = M('wrap')->where(array('id' => $temp_goods['wrap_id']))->find();
                $send_data['order_goods'][$k]['spec'] = $temp_goods_spec;
                $send_data['order_goods'][$k]['goods'] = $temp_goods;
                $send_data['order_goods'][$k]['storestock'] = $temp_storestock;
                $send_data['order_goods'][$k]['tax'] = $temp_tax;
                $send_data['order_goods'][$k]['unit'] = $temp_unit;
                $send_data['order_goods'][$k]['country'] = $temp_country;
                $send_data['order_goods'][$k]['wrap'] = $temp_wrap;
//                array_push($send_data['order_goods'],$temp_goods_spec);
//                array_push($send_data['goods'],$temp_goods);
//                array_push($send_data['storestock'],$temp_storestock);
//                array_push($send_data['tax'],$temp_tax);
//                array_push($send_data['unit'],$temp_unit);
            }

//            echo json_encode($send_data);exit;

//            $send_data = $this->_($order_good);
            $sen_data = $this->_get_oms_data($send_data);
//            $this->sync_data($sen_data,'http://customs.jingjing.shop/api/ecmalltest');
//            lichen 2019/4/22 start
            $url = C('OMS_URL'); #url 地址必须 http://xxxxx
            $port = C('OMS_PORT');
            $t = 10;
            $this->_post_to_oms($url, $port, $t, 'post', $sen_data);
//            lichen 2019/4/22 end
            $pay_str['payment_code'] = I('request.payment_code');
            $pay_str['payment_name'] = I('request.payment_name');
            $pay_str['payment_id'] = 0;

            $this->post_order($order_ids, $pay_str);
        }
    }

    function post_order($id, $payment)
    {

        $order_ids = $id;
        if (!$order_ids) {
            render('10001', '缺少参数');
        }
        $order_info = array(
            'order_amount' => 0,
            'order_sn' => '',
            'pd_amount' => 0,
            'money' => 0,
        );
        $order_ids_array = explode(',', $order_ids);
        if (empty($order_ids_array)) {
            render('19999', '输入参数错误');
        }
        $member_info = M('Member')->where('user_id=' . $this->_user_id)->find();
        $member_money = $member_info['money'];

        foreach ($order_ids_array as $order_id) {
            if (!$order_info0 = M('Order')->where('order_id=' . $order_id . ' AND buyer_id=' . $this->_user_id)->find()) {
                render('10500', '此订单不存在');
            }
            /* 订单有效性判断 */
            if ($order_info0['payment_code'] != 'cod' && $order_info0['status'] != ORDER_PENDING) {
                render('10518', '此订单不是代付款状态');
            }
            $order_info['order_amount'] = bcadd($order_info['order_amount'], $order_info0['order_amount'], 2);
            if (!$order_info['order_sn']) {
                $order_info['order_sn'] = $order_info0['order_sn'];
            } else {
                $order_info['order_sn'] .= ',' . $order_info0['order_sn'];
            }
            /* 使用余额支付 当用户选择部分预付款支付时 */
            if ($order_info0['pd_amount'] != '0.00') {
                if ($member_money >= $order_info0['order_amount']) {
                    $use_pd++;
                    $member_money = bcsub($member_money, $order_info0['order_amount'], 2);
                    //有足够的余额，直接进行支付
                    M('Order')->where('order_id=' . $order_id)->save(array('pd_amount' => $order_info0['order_amount']));
                } else {
                    //没有足够的余额，则把预付款支付设置为余额设置为最大值
                    M('Order')->where('order_id=' . $order_id)->save(array('pd_amount' => $member_money));
                    $order_info0['pd_amount'] = $member_money;
                    $member_money = 0;
                }
            }
            $order_info['pd_amount'] = bcadd($order_info['pd_amount'], $order_info0['pd_amount'], 2);
        }
        $order_info['money'] = bcsub($order_info['order_amount'], $order_info0['pd_amount'], 2);
        //得出订单具体支付金额 END


        $payment_code = $payment['payment_code'];
        $payment_name = $payment['payment_name'];
        if (!$payment_name || !$payment_code) {
            render('10525', '支付为空');
        }
        /* 保存支付方式 */
        $edit_data = array(
            'payment_name' => $payment_name,
            'payment_code' => $payment_code,
            'payment_id' => 0
        );

        M('Order')->where('order_id IN(' . implode(',', $order_ids_array) . ')')->save($edit_data);

        $order_info_array = array();
        $order_info_array['is_order_array'] = 1;
        $order_info_array['item'] = array();
        foreach ($order_ids_array as $order_id) {
            $order_info_array['item'][$order_id] = M('order')->where("order_id=" . $order_id . " AND buyer_id=" . $this->_user_id)->find();
        }

        if ($payment_code == 'wxpay_app') {
            //调用微信支付
            import('Mall.Payment.Wxpay.WxPayment', '', '.php');
            $payment = new \WxPayment();
            $payment->get_payform($order_info_array);
        } elseif ($payment_code == 'alipay_app') {
            //调用支付宝支付
            import('Mall.Payment.Alipay.AliPayment', '', '.php');
            $payment = new \AliPayment();
            $payment->get_payform($order_info_array);
        } else {
            render('19999', '未选择支付');
        }

    }

    /**
     *
     */
    function test()
    {
        $_POST['rec_ids'] = '5';
        $_POST['addr_id'] = '1';
        $_POST['shipping_id'][2] = '1';
    }

    /**
     *    下单完成后清理商品
     */
    function _clear_goods($order_id, $coupon_sn)
    {

        /* 订单下完后清空指定购物车 */
        $model_cart = &m('cart');
        $model_cart->where("user_id=" . $this->_user_id . " AND rec_id IN(" . I('post.rec_ids') . ")")->delete();
        //优惠券信息处理
        if (!empty($coupon_sn)) {
            $sn = trim($coupon_sn);
            M('CouponSn')->where('coupon_sn="' . $sn . '"')->setDec('remain_times');
        }
    }

    /**
     * @api {get} /index.php?m=Home&c=Order&a=get_coupon_list 获取指定店铺我领取的符合条件的优惠券
     */
    function get_coupon_list()
    {
        $store_id = I('request.store_id', 0, 'intval');
        if (empty($store_id)) {
            render('10999', '未设定店铺');
        }
        $cartmap['store_id'] = $store_id;
        $cartmap['user_id'] = $this->_user_id;
        $cart_list = M('cart')->where($cartmap)->select();
        $price = 0;
        foreach ($cart_list as $cart) {
            $price = $price + $cart['price'] * $cart['quantity'];
        }

        /**
         * 检索符合条件的优惠券列表
         */
        $time = time();
        $coupon_list = M('cart')->query("SELECT * FROM " . C('DB_PREFIX') . "coupon_sn couponsn " .
            "LEFT JOIN " . C('DB_PREFIX') . "coupon coupon ON couponsn.coupon_id=coupon.coupon_id " .
            "WHERE coupon.store_id = " . $store_id . " AND couponsn.remain_times >=1 " .
            "AND couponsn.user_id=" . $this->_user_id . " " .
            "AND coupon.start_time <= " . $time . " AND coupon.end_time >= " . $time . " AND coupon.min_amount <= " . $price
        );

        if ($coupon_list) {
            foreach ($coupon_list as $key => $coupon) {
                $coupon_list[$key]['start_time'] = date('Y-m-d', $coupon['start_time']);
                $coupon_list[$key]['end_time'] = date('Y-m-d', $coupon['end_time']);
            }
        }

        render('10000', '', array('coupon_list' => $coupon_list));
    }

    /**
     * @api {get} /index.php?m=Home&c=Order&a=get_shipping_list 获取店铺的物流方式与购物车匹配的价格
     * @apiName 获取店铺的物流方式与购物车匹配的价格
     * @apiGroup All
     * @apiVersion 0.1.0
     * @apiDescription 获取店铺的物流方式与购物车匹配的价格
     *
     * @apiParam {String} store_id 店铺ID
     *
     * @apiSuccess {String} shipping_id 物流方式ID
     * @apiSuccess {String} store_id 店铺ID
     * @apiSuccess {String} shipping_name 物流方式名称
     * @apiSuccess {String} shipping_desc 物流描述
     * @apiSuccess {String} first_price 首件价格
     * @apiSuccess {String} step_price 附加价格
     * @apiSuccess {String} cod_regions 可货到付款地区
     * @apiSuccess {String} enabled 是否开启
     * @apiSuccess {String} sort_order 排序
     * @apiSuccess {String} cod_regions_price 地区价位
     * @apiSuccess {String} shipping_total_price 物流总价
     */
    function get_shipping_list()
    {
        $store_id = I('request.store_id', 0, 'intval');
        if (!$store_id) {
            render('10201', '店铺ID为空');
        }
        //统计当前店铺的所有支付方式
        $map['store_id'] = $store_id;
        $map['enabled'] = 1;
        $shipping_list = M('shipping')->where($map)->select();
        //获取当前店铺的产品数量,因为运费价格有时候是根据产品的数量进行计算的
        $goods_count = M('cart')->where('user_id=' . $this->_user_id . ' AND store_id=' . $store_id)->count();
        if (!empty($shipping_list)) {
            foreach ($shipping_list as $key => $shipping) {
                if ($shipping['step_price'] > 0) {
                    $shipping_list[$key]['shipping_total_price'] = $shipping['first_price'];
                } else {
                    $shipping_list[$key]['shipping_total_price'] = $shipping['first_price'] + ($goods_count - 1) * $shipping['step_price'];
                }
            }
        }
        render('10000', '', array('shipping_list' => $shipping_list));
    }

    function _get_oms_data($data = array())
    {
        $return_array['OrderItets'] = array();
        foreach ($data['order_goods'] as $k => $v) {
            if (!array_key_exists($data['order_goods'][$k]['goods']['goods_id'], $return_array['OrderItets'])) {
//                if(!array_search($data[$k]['spec'],$return_array['OrderItets'][$v['goods_id']]['OrderItemDetails'],true)){
//                    if(!isset($return_array[$v['goods_id']]['OrderItemDetails'])){
//                        $return_array[$v['goods_id']]['OrderItemDetails'] = array();
//                    }
//                $return_array['OrderItets'][$v['goods_id']]['OrderItemDetails'] = array();
                $return_array['OrderItets'][$v['goods_id']]['ProductId'] = $data['order_goods'][$k]['goods']['goods_id'];
                $return_array['OrderItets'][$v['goods_id']]['ItemName'] = $data['order_goods'][$k]['goods']['goods_name'];
                $return_array['OrderItets'][$v['goods_id']]['Unit'] = $data['order_goods'][$k]['unit']['unit_code'];
                $return_array['OrderItets'][$v['goods_id']]['Currency'] = '142';
                $return_array['OrderItets'][$v['goods_id']]['CiqCurrency'] = '156';
                $return_array['OrderItets'][$v['goods_id']]['Country'] = $data['order_goods'][$k]['country']['country_code'];
                $return_array['OrderItets'][$v['goods_id']]['CiqCountry'] = $data['order_goods'][$k]['country']['ciq_code'];
                $return_array['OrderItets'][$v['goods_id']]['WrapTypeCode'] = $data['order_goods'][$k]['wrap']['wrap_code'];
                //                test
                $return_array['OrderItets'][$v['goods_id']]['PurposeCode'] = '9';
                $return_array['OrderItets'][$v['goods_id']]['VendorId'] = $data['seller_id'];
                $return_array['OrderItets'][$v['goods_id']]['StoreId'] = $data['seller_id'];
//                $return_array['OrderItets'][$v['goods_id']]['VendorId'] = 16;

                $return_array['OrderItets'][$v['goods_id']]['ShelfGoodsName'] = $data['order_goods'][$k]['goods']['brand'];

                $return_array['OrderItets'][$v['goods_id']]['ProductSku'] = 'none';
                $return_array['OrderItets'][$v['goods_id']]['BarCode'] = 'none';


            }
            $return_array['OrderItets'][$v['goods_id']]['OrderItemDetails'][] = array(
                'AttributeSku' => $data['order_goods'][$k]['spec']['sku'],
                'Quantity' => $data['order_goods'][$k]['quantity'],
                'Price' => $data['order_goods'][$k]['spec']['price'],
                'TaxRates' => $data['order_goods'][$k]['tax']['consolidated_tax'],
                'OrderTax' => $data['order_goods'][$k]['tax_price'],
                'OrderDiscount' => 0,
                'BarCode' => $data['order_goods'][$k]['spec']['barcode'],
                'TradeType' => $data['order_goods'][$k]['storestock']['stock_style'],
                'PriceInclTax' => $data['order_goods'][$k]['goods']['price'],
                'TotalPrice' => $data['order_goods'][$k]['price_total'],
//                test
                'CustomsChannelId' => $data['order_goods'][$k]['storestock']['stock_id'],
//                'CustomsChannelId' =>  12,
            );
//                    $return_array[$v['goods_id']][''] = array()
//                array_push($return_array[$v['']]['OrderItemDetails'][''],);
//            }else{
//                $return_array['OrderItets'][$v['goods_id']] = array();

//            }
        }
        $address_str = str_replace('-', ',', $data['order_extm']['region_name']);
//        $address_str = $this->emptyreplace($data['order_extm']['region_name']);
        $address_str = $address_str . $data['order_extm']['address'];
        $return_array['OrderStatusId'] = 10;
        $return_array['ShippingStatusId'] = 20;
        $return_array['PaymentStatusId'] = 10;
        $return_array['PaymentMethodSystemName'] = 'none';
        $return_array['ShippingMethod'] = 'ground';
        $return_array['CustomerCurrencyCode'] = '142';
        $return_array['AuthorizationTransactionResult'] = 'none';
        $return_array['OrderTotal'] = $data['goods_amount'];
        $return_array['AffiliateId'] = 0;
        $return_array['RefundedAmount'] = 0;
        $return_array['CreatedOnUtc'] = date("Y-m-d H:i:s");
        $return_array['OrderNo'] = $data['order_sn'];
        $return_array['BuyerName'] = $this->_real_name;
        $return_array['BuyerTelephone'] = $data['phone_mob'];
        $return_array['BuyerRegNo'] = $data['phone_mob'];
        $return_array['BuyerIdType'] = 1;
        $return_array['BuyerIdNumber'] = $this->_user_no;
        $return_array['PayCode'] = 'none';
        $return_array['PayName'] = 'none';
        $return_array['PayTransactionId'] = 'none';
        $return_array['Consignee'] = $data['order_extm']['consignee'];
        $return_array['ConsigneeTelephone'] = $data['order_extm']['phone_mob'];
        $return_array['ConsigneeAddress'] = $address_str;
        $return_array['IdCard'] = $data['order_extm']['user_no'];
        $return_array['IdType'] = 1;
        $return_array['EtradeCountryCode'] = '156';
        $return_array['OrderItems'] = array();
        $return_array['OrderItems'] = array_values($return_array['OrderItets']);
        return $return_array;

    }

    function _post_to_oms($url, $port = 80, $t = 30, $method = 'get', $data = null)
    {
        $info = parse_url($url);
        $fp = fsockopen('ssl://' . $info['host'], $port, $errno, $errstr, $t);
        // 判断是否有数据
        if (isset($data) && !empty($data)) {
            $query = http_build_query($data); // 数组转url 字符串形式
        } else {
            $query = null;
        }
        // 如果用户的$url "http://www.manongjc.com/";  缺少 最后的反斜杠
        if (!isset($info['path']) || empty($info['path'])) {
            $info['path'] = "/index.html";
        }
        // 判断 请求方式
        if ($method == 'post') {
            $head = "POST " . $info['path'] . " HTTP/1.0" . PHP_EOL;
        } else {
            $head = "GET " . $info['path'] . "?" . $query . " HTTP/1.0" . PHP_EOL;
        }

        $head .= "Host: " . $info['host'] . PHP_EOL; // 请求主机地址
        $head .= "Referer: https://" . $info['host'] . ':' . $port . $info['path'] . PHP_EOL;
        if (isset($data) && !empty($data) && ($method == 'post')) {
            $head .= "Content-type: application/x-www-form-urlencoded" . PHP_EOL;
            $head .= "Content-Length: " . strlen(trim($query)) . PHP_EOL;
            $head .= PHP_EOL;
            $head .= trim($query);
        } else {
            $head .= PHP_EOL;
        }
//        var_dump($head);exit;
        $write = fputs($fp, $head); //写入文件(可安全用于二进制文件)。 fputs() 函数是 fwrite() 函数的别名
        while (!feof($fp)) {
            $line = fread($fp, 4096);
//            echo $line;
        }
    }

    function emptyreplace($str)
    {
        $str = preg_replace('/\s+/', ',', $str);
        return $str;
    }

    function sync_data($url, $data_string)
    {
        $data_string = json_encode($data_string);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($data_string))
        );
        ob_start();
        $res = curl_exec($ch);
        if (!$res) {
            return array('MessageCode' => 2, 'ErrorMsg' => '同步失败');
        } else {
            return json_decode($res, true);
        }
        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $return_content = ob_get_contents();
        ob_end_clean();

        return array('code' => $return_code, 'result' => $return_content);
    }
}